//
//  PlSUpdateInfo.m
//  PlugSuit
//
//  Created by ∞ on 20/12/07.
//  Copyright 2007 Emanuele Vulcano (infinite-labs.net). All rights reserved.
//

#import "PlSUpdateInfo.h"

#define kPlSMostCurrentVersionKey @"PlSMostCurrentVersion"
#define kPlSMostCurrentVersionStringKey @"PlSMostCurrentVersionString"
#define kPlSDownloadURLKey @"PlSDownloadURL"
#define kPlSMoreInfoURLKey @"PlSMoreInfoURL"
#define kPlSDescriptionsKey @"PlSDescriptions"

@implementation PlSUpdateInfo

@synthesize newVersionString, newVersion, descriptions, downloadURL, moreInfoURL;

- (id) initWithContentsOfURL:(NSURL*) url {
	if (![super init]) return nil;
	
	NSDictionary* d = nil;
	@try {
		d = [NSDictionary dictionaryWithContentsOfURL:url];
	} @catch (NSException* ex) {}
	
	if (!d) { [self release]; return nil; }
	
	id n = [d objectForKey:kPlSMostCurrentVersionKey];
	id dURL = [d objectForKey:kPlSDownloadURLKey];
	id mURL = [d objectForKey:kPlSMoreInfoURLKey];
	id de = [d objectForKey:kPlSDescriptionsKey];
	
	if (!n || !dURL || !mURL || !de || !([dURL hasPrefix:@"http://"] || [dURL hasPrefix:@"https://"]) || !([mURL hasPrefix:@"http://"] || [mURL hasPrefix:@"https://"]) || ![de objectForKey:@"en"]) {
		[self release];
		return nil;
	}
	
	self.newVersionString = [d objectForKey:kPlSMostCurrentVersionStringKey];
	self.newVersion = [n doubleValue];
	self.downloadURL = [NSURL URLWithString:dURL];
	self.moreInfoURL = [NSURL URLWithString:mURL];
	self.descriptions = de;
	
	return self;
}

- (NSString*) preferredDescription {
	return [self preferredDescriptionForLocale:[NSLocale currentLocale]];
}

- (NSString*) preferredDescriptionForLocale:(NSLocale*) l {
	NSString* desc = [self.descriptions objectForKey:[l objectForKey:NSLocaleLanguageCode]];
	if (!desc)
		desc = [self.descriptions objectForKey:@"en"];
	if (!desc && [self.descriptions count] > 0)
		desc = [[self.descriptions allValues] objectAtIndex:0];
	
	return desc;
}

- (void) dealloc {
	self.newVersionString = nil;
	self.downloadURL = nil;
	self.moreInfoURL = nil;
	self.descriptions = nil;
	
	[super dealloc];
}

@end
